package com.cmfi.controller;

import java.util.List;
import java.util.Map;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.cmfi.domain.PlanWorkOrder;
import com.cmfi.service.inter.PlanWorkOrderService;
import com.cmfi.utils.Code;
import com.cmfi.utils.Result;

/**
 * REST controller for managing {@link com.azure.forklift.domain.ForkliftPlan}.
 */
@RestController
@RequestMapping("/api")
public class PlanWorkOrderController {

    private final Logger log = LoggerFactory.getLogger(PlanWorkOrderController.class);

	@Autowired
	private PlanWorkOrderService planWorkOrderService;

    /**
     * {@code GET  /forklift-plans} : get all the forkliftPlans.
     *
     * @param params 获取plans.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of forkliftPlans in body.
     */
	@GetMapping("/planworkorder")
	@PreAuthorize("hasAuthority('plan')")
	public Result getAllPlanWorkOrders(@RequestParam Map<String, Object> params) {
		log.info("[PlanWorkOrderController][getAllPlanWorkOrders] parameters:{}", params);
		List<PlanWorkOrder> planList = null;
		long total = 0;
		try {
			if (params == null) {
				return new Result(Code.GET_ERR, "入参为空");
			}
			Integer pageNum = 0;
			Integer pageSize = 0;
			if (params.containsKey("pageNum")) {
				pageNum = Integer.parseInt(params.get("pageNum").toString());
			}
			if (params.containsKey("pageSize")) {
				pageSize = Integer.parseInt(params.get("pageSize").toString());
			}
			planList = planWorkOrderService.findByPage(pageNum, pageSize);
			total = planList.size();
		} catch (Exception e) {
			log.error("[PlanWorkOrderController][getAllPlanWorkOrders] e:{}", e);
			return new Result(Code.GET_ERR, e.getMessage());
		}
		return new Result(Code.GET_OK, planList, total);
	}

    /**
     * {@code GET  /forklift-plans/:id} : get the "id" forkliftPlan.
     *
     * @param id the id of the forkliftPlan to retrieve.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the forkliftPlan, or with status {@code 404 (Not Found)}.
     */
	@GetMapping("/planworkorder/{id}")
	@PreAuthorize("hasAuthority('plan')")
	public Result getPlanWorkOrder(@PathVariable Long id) {
		log.info("[PlanWorkOrderController][getPlanWorkOrder] id: {}", id);
		PlanWorkOrder planWorkOrder = null;
		try {
			planWorkOrder = planWorkOrderService.findOne(id);
		} catch (Exception e) {
			log.error("[PlanWorkOrderController][getPlanWorkOrder] id: {}", id);
			return new Result(Code.GET_ERR, e.getMessage());
		}
		return new Result(Code.GET_OK, planWorkOrder);
	}

    /**
     * {@code DELETE  /forklift-plans/:id} : delete the "id" forkliftPlan.
     *
     * @param id the id of the forkliftPlan to delete.
     * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
     */
    @DeleteMapping("/planworkorder/{id}")
    @PreAuthorize("hasAuthority('plan')")
	public Result deletePlanWorkOrder(@PathVariable Long id) {
		log.info("[PlanWorkOrderController][deletePlanWorkOrder] id: {}", id);
		try {
			planWorkOrderService.delete(id);
		} catch (Exception e) {
			log.error("[PlanWorkOrderController][deletePlanWorkOrder] e: ", e);
			return new Result(Code.GET_ERR, e.getMessage());
		}
		return new Result(Code.DELETE_OK, id);
	}


    /**
     * {@code GET  /forklift-plans/getPlanByVinCode?vinCode={vinCode} : get the "id" forkliftPlan.
     *
     * @param vinCode the id of the forkliftPlan to retrieve.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the forkliftPlan, or with status {@code 404 (Not Found)}.
     */
	@GetMapping("/planworkorder/getPlanByVinCode")
	@PreAuthorize("hasAuthority('plan')")
	public Result getPlanByVinCode(@RequestParam String vinCode) {
		log.debug("[PlanWorkOrderController][getPlanByVinCode] vinCode: {}", vinCode);
		PlanWorkOrder planWorkOrder = null;
		try {
			planWorkOrder = planWorkOrderService.findByVinCode(vinCode);
		} catch (Exception e) {
			log.debug("[PlanWorkOrderController][getPlanByVinCode] e:", e);
		}
		return new Result(Code.GET_OK, planWorkOrder);
	}

    /**
     * {@code GET  /forklift-plans} : get all the forkliftPlans.
     *
     * @param pageable the pagination information.
     * @param request a {@link ServerHttpRequest} request.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of forkliftPlans in body.
     */
	@GetMapping(value = "/planworkorder/findAllByDate")
	@PreAuthorize("hasAuthority('plan')")
	public Result getAllPlanWorkOrdersByDate(@RequestParam Map<String, Object> params) {
		log.info("[PlanWorkOrderController][getAllPlanWorkOrdersByDate] params:{}", params);
		if (params == null) {
			return new Result(Code.GET_ERR, "入参为空");
		}
		List<PlanWorkOrder> planList = null;
		long total = 0;
		try {
			int pageNum = 0;
			int itemNum = 0;
			String date = null;
			if (params.containsKey("pageNum")) {
				pageNum = Integer.parseInt(params.get("pageNum").toString());
			}
			if (params.containsKey("pageSize")) {
				itemNum = Integer.parseInt(params.get("pageSize").toString());
			}
			if (params.containsKey("date")) {
				date = params.get("date").toString();
			}
			planList = planWorkOrderService.findByDateAndPage(date, pageNum, itemNum);
			total = planList.size();
		} catch (Exception e) {
			log.debug("[PlanWorkOrderController][getAllPlanWorkOrdersByDate] e:", e);
			return new Result(Code.GET_ERR, e.getMessage());
		}
		return new Result(Code.GET_OK, planList, total);
	}

    /**
	 * {@code GET  /forklift-plans} : get all the forkliftPlans.
	 *
	 * @param pageable the pagination information.
	 * @param request  a {@link ServerHttpRequest} request.
	 * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list
	 *         of forkliftPlans in body.
	 */
	@GetMapping(value = "/planworkorder/findAllByStatusAndDate")
	@PreAuthorize("hasAuthority('plan')")
	public Result getAllPlanWorkOrdersByStatus(@RequestParam Map<String, Object> params) {
		log.info("[PlanWorkOrderController][getAllPlanWorkOrdersByStatus] params:{}", params);
		List<PlanWorkOrder> planList = null;
		long total = 0;
		try {
			int pageNum = 0;
			int pageSize = 0;
			String date = null;
			String status = null;
			if (params.containsKey("pageNum")) {
				pageNum = Integer.parseInt(params.get("pageNum").toString());
			}
			if (params.containsKey("pageSize")) {
				pageSize = Integer.parseInt(params.get("pageSize").toString());
			}
			if (params.containsKey("date")) {
				date = (String) params.get("date");
			}
			if (params.containsKey("status")) {
				status = (String) params.get("status");
			}
			planList = planWorkOrderService.findByDateStatusAndPage(date, status, pageNum, pageSize);
			total = planList.size();
		} catch (Exception e) {
			log.debug("[PlanWorkOrderController][getAllPlanWorkOrdersByStatus] e:", e);
			return new Result(Code.GET_ERR, e.getMessage());
		}
		return new Result(Code.GET_OK, planList, total);
	}
	
	//导入工单
    @PostMapping("/uploadFile")
    @PreAuthorize("hasAuthority('plan')")
    public Result handleFileUpload(@RequestParam("file") MultipartFile file) {
    	try {
    		log.info("[PlanWorkOrderController][handleFileUpload] handleFileUpload");
    		PlanWorkOrder excelPlan = planWorkOrderService.importExcel(file);
			return new Result(Code.SAVE_OK, excelPlan);
		} catch (Exception e) {
			log.info("[PlanWorkOrderController][handleFileUpload] e,", e);
			return new Result(Code.SAVE_ERR, e.getMessage());
		}
    }
    
    //和MES系统对接，导入工单
    @PostMapping("/uploadFilebyMES")
    @PreAuthorize("hasAuthority('plan')")
    public Result handleFileUploadbyMES() {
    	try {
    		 // 使用HttpClient发送HTTP请求获取MES系统中的生产数据
             CloseableHttpClient httpclient = HttpClients.createDefault();
			 HttpGet httpGet = new HttpGet();
			 CloseableHttpResponse response = httpclient.execute(httpGet);

			 // 读取响应内容
			 String responseBody = EntityUtils.toString(response.getEntity());
			 
			planWorkOrderService.saveFromMES(responseBody);//根据具体的格式来修改
			return new Result(Code.SAVE_OK, "success");
		} catch (Exception e) {
			log.info("[PlanWorkOrderController][handleFileUploadbyMES] e,", e);
			return new Result(Code.SAVE_ERR, e.getMessage());
		}
    }
}
